package cn.wlinker.driver.modbus.tcp;

import cn.hutool.core.bean.BeanUtil;
import cn.wlinker.driver.common.AbstractDriver;
import cn.wlinker.driver.common.CommonConnBean;
import cn.wlinker.driver.modbus.tcp.domain.ModbusBean;
import cn.wlinker.driver.modbus.tcp.domain.ModbusRes;
import cn.wlinker.driver.modbus.tcp.utils.ModbusHelper;
import cn.wlinker.driver.modbus.tcp.utils.ModbusMasterHelper;
import com.serotonin.modbus4j.ModbusMaster;
import lombok.SneakyThrows;

import java.util.Map;

/**
 * modbus tcp驱动
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/10/9
 */
public class ModbusTcpDriver extends AbstractDriver<CommonConnBean, ModbusBean, ModbusRes> {

    public ModbusTcpDriver(Map<String, Object> connectionMap) {
        super(connectionMap);
    }

    @Override
    protected String getConnectionKey() {
        return connectionMap.get("ip").toString();
    }

    @Override
    public CommonConnBean getConnectionBean() {
        return BeanUtil.toBean(connectionMap, CommonConnBean.class);
    }

    @Override
    public Boolean open() throws Exception {
        CommonConnBean connectionBean = getConnectionBean();
        ModbusMaster master = ModbusMasterHelper.getMaster(connectionBean.getIp(), connectionBean.getPort());
        return master.isConnected();
    }

    @Override
    public Boolean close() {
        CommonConnBean connectionBean = getConnectionBean();
        return ModbusMasterHelper.removeMaster(connectionBean.getIp(), connectionBean.getPort());
    }

    @SneakyThrows
    @Override
    public Boolean isOpen() {
        return open();
    }

    @Override
    @SneakyThrows
    public ModbusRes read(ModbusBean dto) {
        CommonConnBean connectionBean = getConnectionBean();
        return ModbusHelper.read(connectionBean.getIp(), connectionBean.getPort(), dto);
    }

    @SneakyThrows
    @Override
    public Boolean write(ModbusBean dto) {
        CommonConnBean connectionBean = getConnectionBean();
        return ModbusHelper.write(connectionBean.getIp(),connectionBean.getPort(),dto);
    }
}
